//给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。 
//
// 
//
// 示例 1: 
//
// 
//Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
//Output: [3,9,20,null,null,15,7]
// 
//
// 示例 2: 
//
// 
//Input: preorder = [-1], inorder = [-1]
//Output: [-1]
// 
//
// 
//
// 提示: 
//
// 
// 1 <= preorder.length <= 3000 
// inorder.length == preorder.length 
// -3000 <= preorder[i], inorder[i] <= 3000 
// preorder 和 inorder 均无重复元素 
// inorder 均出现在 preorder 
// preorder 保证为二叉树的前序遍历序列 
// inorder 保证为二叉树的中序遍历序列 
// 
// Related Topics 树 数组 哈希表 分治 二叉树 
// 👍 1354 👎 0

package com.cute.leetcode.editor.cn;
public class ConstructBinaryTreeFromPreorderAndInorderTraversal {
    public static void main(String[] args) {
        Solution solution = new ConstructBinaryTreeFromPreorderAndInorderTraversal().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    /**
     * 使用前序遍历与中序遍历构二叉树
     * 这个题目和下一道题目比较像，只是切割时是有前序遍历的第一个元素切割的
     * 注意区间仍选择左开右闭
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return travel(preorder, 0, preorder.length, inorder, 0, inorder.length);
    }

    public TreeNode travel(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd){
        if (preBegin == preEnd) return null;//空节点
        int val = preorder[preBegin];//取前序遍历的第一个节点
        TreeNode node = new TreeNode(val);
        if (inEnd - inBegin == 1) return node;//叶子节点，因为是左开右闭的区间

        int index;//寻找分割点
        for (index = inBegin; index < inEnd; index++) if (inorder[index] == val) break;

        int inLeftBegin = inBegin;
        int inLeftEnd = index;
        int inRightBegin = index + 1;
        int inRightEnd = inEnd;

        int preLeftBegin = preBegin+1;
        int preLeftEnd = preLeftBegin + index - inLeftBegin;
        int preRightBegin = preLeftBegin + index - inLeftBegin;
        int preRightEnd = preEnd;

        node.left = travel(preorder, preLeftBegin, preLeftEnd, inorder, inLeftBegin, inLeftEnd);
        node.right = travel(preorder, preRightBegin, preRightEnd, inorder, inRightBegin, inRightEnd);
        return node;

    }
}
//leetcode submit region end(Prohibit modification and deletion)
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
}